<template>
	<view style="padding-bottom: 200rpx;" class="wrapper bg-linear">
		<view class="wrapper shadow1 border-r-10 bg-color m-b-12">
			<!-- 快递大小选择按钮组 -->
			<view class="flex flex-row items-center p-12">
				<view class="t-16 t-bold mr-4">快递大小</view>
				<view class="flex-1 flex flex-row flex-nowrap overflow-x-auto pb-2">
					<view class="express-size-btn" :class="{ 'active': size === '小' }" @click="selectSize('小')">小</view>
					<view class="express-size-btn" :class="{ 'active': size === '中' }" @click="selectSize('中')">中</view>
					<view class="express-size-btn" :class="{ 'active': size === '大' }" @click="selectSize('大')">大</view>
					<view class="express-size-btn" :class="{ 'active': size === '特大' }" @click="selectSize('特大')">特大
					</view>
				</view>
			</view>

			<ppl-textarea placeholder="输入快递信息" @onChange="onChangeNeed">
				<view slot="title" class="t-14">取件信息</view>
			</ppl-textarea>

			<!-- 修改点：传递初始图片并监听文件变化 -->
			<ppl-upload :initial-files="imgs.split(',').filter(url => url)" @file-change="handleFileChange"
				:max-count="4" />

			<ppl-infoField :use-custom="true">
				<view>
					<van-field :value="address" :required="true" placeholder="请选择地址" error-message-align="right"
						:error-message="errors.address" is-link clickable readonly input-align="right"
						@click-input="toSelectAddress">
						<view slot="label" class="color8">
							取件地址
						</view>
					</van-field>

					<van-field :value="expressNum" :required="true" placeholder="请输入垃圾数量" error-message-align="right"
						:error-message="errors.kdNum" input-align="right" type="digit" @blur="handleKdNumBlur">
						<view slot="label" class="color8">
							快递数量
						</view>
					</van-field>
					<!-- 移动金额模块到快递数量下方 -->
					<van-field :value="bonus" :required="true" placeholder="输入金额" error-message-align="right"
						:error-message="errors.bonus" input-align="right" @change="onChangeBonus">
						<view slot="label" class="color8">
							金额
						</view>
					</van-field>
				</view>
			</ppl-infoField>
			<ppl-textarea placeholder="请输入您想说的话…" @onChange="onChangeRemake">
				<view slot="title" class="p-t-12 t-14">备注信息（所有人可见）</view>
			</ppl-textarea>
		</view>

		<ppl-tips :tips="tips" />
		<ppl-pay @submit="submit" :price="price" />
		<ppl-kd :show="showSelectors" @close="close" @onSelected="onSelected" position="bottom" />
		<van-popup :show="show" @close="show = false" position="bottom">
			<van-picker :show-toolbar="true" :columns="columns" @change="onChangeTime" @confirm="confirmTime" />
		</van-popup>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		watch,
		nextTick
	} from 'vue'
	import {
		getGoodsSize,
		postNeed
	} from '@/api/index.js'
	import {
		DELIVERYTIME,
		GENDER
	} from '@/package/constants/index.js'
	import {
		getList,
		payFlag
	} from '@/utils/index.js'
	import {
		addCampusOrder
	} from '@/package/api/insertList.js'
	import {
		getPaymentInfoTo,
		getYueZhiFu
	} from '@/api/index.js'
	import {
		updateCampusOrder,
		deleteCampusOrder
	} from '@/package/api/update.js'

	// 地址相关响应式数据
	const address = ref(''); // 收件地址
	let addressListener = null; // 存储事件监听器引用
	const addressSelectionInProgress = ref(false); // 跟踪地址选择过程

	// 获取当前用户ID
	const userId = ref(uni.getStorageSync('userId') || '');

	// 初始化所有响应式数据
	const expressNum = ref('1')
	const checked = ref(true)
	const bonus = ref('')
	const sizeIndex = ref('')
	const expressSize = ref([]);
	const price = ref(0);
	const cid = ref('');
	const name = ref('');
	const showSelectors = ref(false);
	const show = ref(false)
	const kd = ref('');
	const time = ref('');
	const sex = ref('');
	const columns = ref([]);
	const currentSelect = ref('');
	const need = ref('');
	const remake = ref('');
	const currentPrice = ref('0'); // 默认基础价格设为0
	const imgs = ref(''); // 存储图片URL，用逗号分隔
	const size = ref('小');
	const tips = ref(['请提前下好单，联系电话留对，及时与接单员沟通', '距离过长，无人接单建议增加金额', '发布需要实名认证审核通过'])
	const errors = reactive({
		address: '',
		kd: '',
		kdNum: '',
		bonus: '' // 移除时间和性别的错误验证
	});

	// 生成唯一订单号
	const generateOrderNo = () => {
		const timestamp = new Date().getTime();
		const randomNum = Math.floor(Math.random() * 1000);
		const schoolId = uni.getStorageSync('school_id') || '000';
		return `ORD${schoolId}${timestamp}${randomNum}`;
	}

	const selectSize = (selectedSize) => {
		size.value = selectedSize;
		// 不再设置默认金额，仅记录选择的快递大小
		updatePrice();
	}

	const handleKdNumBlur = (e) => {
		const inputValue = e.detail || expressNum.value;
		const validValue = inputValue.replace(/[^\d]/g, '');
		expressNum.value = validValue;

		if (!validValue || Number(validValue) < 1) {
			errors.kdNum = '请输入大于0的数字';
			expressNum.value = '1';
		} else {
			errors.kdNum = '';
		}
		updatePrice();
	}

	const onChangeKd = (e) => {
		kd.value = e.detail;
		if (kd.value) errors.kd = '';
	}

	const updatePrice = () => {
		// 基础价格始终为0，总价仅由用户输入的bonus决定
		price.value = bonus.value ? Number(bonus.value) : 0;
	}

	const onChangeBonus = (e) => {
		bonus.value = e.detail;
		if (bonus.value) errors.bonus = '';
		updatePrice();
	}

	// 点击选择地址
	const toSelectAddress = () => {
		// 标记正在进行地址选择
		addressSelectionInProgress.value = true;

		// 先移除之前的监听器，确保干净的状态
		if (addressListener) {
			uni.$off('selectAddress', addressListener);
			uni.$off('selectPickAddress', addressListener);
			addressListener = null;
		}

		// 创建新的监听器
		addressListener = (res) => {
			console.log('接收到地址选择事件:', res);

			// 只处理在地址选择过程中发生的事件
			if (addressSelectionInProgress.value) {
				if (res && (res.building || res.detailAddress)) {
					address.value = `${res.building || ''} ${res.detailAddress || ''}`.trim();
					errors.address = ''; // 清除地址验证错误
					console.log('更新后的地址:', address.value);
				} else if (res && res.address) {
					address.value = res.address;
					errors.address = '';
				}

				// 完成地址选择流程
				addressSelectionInProgress.value = false;
			}
		};

		// 添加新的监听器
		uni.$on('selectAddress', addressListener);
		uni.$on('selectPickAddress', addressListener);

		// 跳转到地址选择页面
		uni.navigateTo({
			url: '/package/pages/address/address?isPickAddress=true'
		});
	}

	const close = () => {
		showSelectors.value = false;
	}

	const onChangeRemake = (e) => {
		remake.value = e;
	}

	const onChangeNeed = (e) => {
		need.value = e;
	}

	const onChangeAddress = (e) => {
		checked.value = e.detail;
		if (address.value) errors.address = '';
	}

	// 修改点：处理图片上传后的文件变化
	const handleFileChange = (fileUrls) => {
		console.log('接收到图片URL列表:', fileUrls);
		imgs.value = fileUrls.join(',');
		console.log('更新后的图片URL:', imgs.value);
	};

	const submit = async () => {
		// 验证所有必填字段，移除时间和性别的验证
		if (!address.value) {
			errors.address = '请选择地址';
			return;
		}
		// if (!kd.value) {
		// 	errors.kd = '请输入快递商家';
		// 	return;
		// }
		if (!expressNum.value || Number(expressNum.value) < 1) {
			errors.kdNum = '请输入大于0的数字';
			return;
		}
		if (!bonus.value) {
			errors.bonus = '请输入金额';
			return;
		}

		// 新增：验证支付金额必须大于1
		const amount = Number(bonus.value);
		if (amount < 1) {
			errors.bonus = '支付金额必须大于1元';
			return;
		}

		// 从本地存储中获取查看是否实名
		if (uni.getStorageSync('isrealnameauthenticated') != 1) {
			// 表示未实名
			uni.showToast({
				title: '未进行实名认证,不能发布任务',
				icon: 'none',
				duration: 1000
			});
			return
		}

		try {
			const campusOrder = {
				orderNo: generateOrderNo(),
				orderType: 2, // 快递代寄
				orderStatus: 0,
				payAmount: price.value.toString(),
				payStatus: 0,
				expressSize: size.value === '小' ? 1 : size.value === '中' ? 2 : size.value === '大' ? 3 : 4,
				startPlace: address.value,
				endPlace: kd.value,
				phone: uni.getStorageSync('userPhone') || '',
				imageInfo: imgs.value,
				pickupInfo: need.value,
				schoolId: uni.getStorageSync('school_id'),
				userId: userId.value
			};

			console.log('提交的订单数据:', JSON.stringify(campusOrder));

			// 调用addCampusOrder接口
			const addRes = await addCampusOrder(JSON.stringify(campusOrder));
			console.log('订单添加结果:', addRes);

			if (addRes.data > 0) {
				// 显示支付方式选择
				uni.showActionSheet({
					itemList: ['微信支付', '余额支付'],
					success: function(res) {
						switch (res.tapIndex) {
							case 0: // 微信支付
								handleWechatPay(campusOrder.orderNo, addRes.data);
								break;
							case 1: // 余额支付
								handleBalancePay(campusOrder.orderNo, addRes.data);
								break;
							default:
								console.log('用户取消支付');
						}
					},
					fail: function(err) {
						console.log('显示支付方式选择失败:', err);
						// 可以选择默认使用微信支付或提示用户
						handleWechatPay(campusOrder.orderNo, addRes.data);
					}
				});
			} else {
				uni.showToast({
					title: addRes.msg || '订单添加失败',
					duration: 1000,
					icon: 'none'
				});
			}
		} catch (e) {
			console.error('提交订单出错:', e);
			uni.showToast({
				title: '操作失败，请重试',
				duration: 1000,
				icon: 'none'
			});
		}
	}

	// 余额支付处理函数
	const handleBalancePay = async (orderNo, orderId) => {
		try {
			// 准备余额支付参数
			const yueZhiFuParams = {
				orderNo: orderNo,
				totalAmount: price.value.toFixed(2) // 使用toFixed确保两位小数
			};

			console.log('余额支付参数:', yueZhiFuParams);

			// 显示加载中
			uni.showLoading({
				title: '支付处理中...'
			});

			// 调用余额支付接口
			const payRes = await getYueZhiFu(yueZhiFuParams);

			// 隐藏加载
			uni.hideLoading();

			if (payRes.code === 200) {
				// 余额支付成功
				uni.showModal({
					title: '支付结果',
					content: payRes.message || '余额支付成功',
					showCancel: false,
					success: async () => {
						try {
							// 更新订单状态为已支付
							const response = await updateCampusOrder({
								orderNo: orderNo,
								payStatus: 1,
								orderStatus: 1,
								paymentType: 1
							});

							console.log('订单状态更新成功:', response);

							// 重置表单
							resetForm();

						} catch (error) {
							console.error('订单状态更新失败:', error);
							uni.showToast({
								title: '订单状态更新失败，请重试',
								icon: 'none'
							});
						}
					}
				});
			} else if (payRes.code === 400) { // 假设后端余额不足返回400错误
				// 余额不足提示
				uni.showToast({
					title: payRes.message || '账户余额不足，请先充值',
					icon: 'none'
				});

				// 删除未支付的订单
				deleteCampusOrder(JSON.stringify({
					id: orderId
				}));
			}
		} catch (error) {
			console.error('余额支付处理异常:', error);
			uni.hideLoading();
			uni.showToast({
				title: '支付处理失败，请重试',
				icon: 'none'
			});
		}
	};

	// 新增重置表单函数
	const resetForm = () => {
		// 重置表单数据，移除时间和性别相关字段
		address.value = '';
		kd.value = '';
		expressNum.value = '1';
		bonus.value = '';
		need.value = '';
		remake.value = '';
		size.value = '小';
		imgs.value = '';
		price.value = 0;

		// 清除错误提示
		Object.keys(errors).forEach(key => {
			errors[key] = '';
		});

		// 重置当前价格
		currentPrice.value = '0';
	};

	// 微信支付处理函数
	const handleWechatPay = async (orderNo, orderId) => {
		try {
			let payData = {
				orderNo: orderNo
			}
			let payres = await getPaymentInfoTo(payData);
			console.log(payres, 123)
			if (payres.code == 200) {

				wx.requestPayment({
					timeStamp: payres.data.jsConfig.timeStamp,
					nonceStr: payres.data.jsConfig.nonceStr,
					package: payres.data.jsConfig.packageVal,
					paySign: payres.data.jsConfig.paySign,
					signType: payres.data.jsConfig.signType, // 该参数为固定值
					success(res) {
						uni.showToast({
							title: '支付成功',
							icon: 'none'
						})
						// 更新订单状态为已支付
						updateCampusOrder({
							orderNo: orderNo,
							payStatus: 1,
							orderStatus: 1,
							paymentType: 0
						});

						// 重置表单
						resetForm();

						// 跳转页面
						// setTimeout(() => {
						// 	uni.switchTab({
						// 		url: '/pages/index/index'
						// 	});
						// }, 1500);
					},
					fail(err) {
						// 支付失败回调
						console.error('唤起支付组件失败：', err);
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
						// 删除未支付的订单
						deleteCampusOrder(JSON.stringify({
							id: orderId
						}));
					}
				});
			}
		} catch (error) {
			console.error('微信支付处理异常:', error);
			uni.showToast({
				title: '支付处理失败，请重试',
				icon: 'none'
			});
		}
	};

	// 页面显示时
	onShow(() => {
		// 检查用户是否已登录
		if (!userId.value) {
			userId.value = uni.getStorageSync('userId') || '';
		}

		// 如果不是在地址选择过程中，确保没有活跃的监听器
		if (!addressSelectionInProgress.value && addressListener) {
			uni.$off('selectAddress', addressListener);
			uni.$off('selectPickAddress', addressListener);
			addressListener = null;
		}
	})

	// 页面加载时的数据初始化
	onLoad((options) => {
		// 保存传递的参数
		name.value = options.name || '';
		cid.value = options.cid || '';

		// 初始化用户ID
		if (!userId.value) {
			userId.value = uni.getStorageSync('userId') || '';
		}

		// 初始化表单数据
		resetForm();

		// 清空图片（确保页面加载时没有残留图片）
		imgs.value = '';
	})

	// 使用onUnload确保在页面卸载前移除监听器
	onUnload(() => {
		if (addressListener) {
			uni.$off('selectAddress', addressListener);
			uni.$off('selectPickAddress', addressListener);
			addressListener = null;
		}
		addressSelectionInProgress.value = false;
	})
</script>

<style scoped>
	/* 样式保持不变 */
	::v-deep .van-cell {
		padding-left: 0;
		padding-right: 0;
	}

	::v-deep .van-submit-bar__bar {
		justify-content: space-between;
	}

	::v-deep .van-button--danger {
		background-color: #3c91ff;
		border-radius: 10rpx;
	}

	::v-deep .van-submit-bar__bar {
		box-shadow: -2px -1px 5px 0px rgba(0, 0, 0, 0.05);
	}

	::v-deep .input-placeholder {
		color: #3c91ff !important;
	}

	::v-deep .van-cell--required:before {
		left: -7px;
	}

	::v-deep .van-cell:after {
		right: 0;
		left: 0;
	}

	/* 新增按钮容器样式 */
	.flex-nowrap {
		flex-wrap: nowrap !important;
	}

	.overflow-x-auto {
		overflow-x: auto !important;
		-webkit-overflow-scrolling: touch;
		/* 优化移动端滚动体验 */
	}

	.pb-2 {
		padding-bottom: 2rpx;
	}

	/* 保持原有按钮样式不变 */
	.express-size-btn {
		width: 65px;
		height: 40px;
		line-height: 40px;
		border-radius: 20rpx;
		border: 1px solid #ddd;
		font-size: 22rpx;
		color: #666;
		white-space: nowrap;
		text-align: center;
		background-color: #fff;
		float: left;
		margin-right: 10px;
	}

	.express-size-btn.active {
		border-color: #3c91ff;
		color: #3c91ff;
		background-color: rgba(60, 145, 255, 0.1);
	}
</style>